#include "server.h"

void* threadFunc(void* arg){
    threadPool_t* threadPool = (threadPool_t *)arg;

    while(1){
        pthread_mutex_lock(&threadPool->mutex);
        while(threadPool->exitFlag == 0 && threadPool->taskQueue.size <= 0){
            pthread_cond_wait(&threadPool->cond, &threadPool->mutex);
        }
        if(threadPool->exitFlag == 1){
            printf("worker is going to exit");
            pthread_mutex_unlock(&threadPool->mutex);
            pthread_exit(NULL);
        }
        int netfd = threadPool->taskQueue.head->netfd;
        deQueue(&threadPool->taskQueue);
        pthread_mutex_unlock(&threadPool->mutex);

        //接收并检查token
        train_t train;
        char token[200];
        recvn(netfd,&train,sizeof(train));
        memcpy(token,train.data,train.length);
        char usrname[128];
        recvn(netfd,&train,sizeof(train));
        memcpy(usrname,train.data,train.length);

        train.tag = checktoken(usrname,token);
        send(netfd,&train,sizeof(train),MSG_NOSIGNAL);
        if(train.tag == 1){
            close(netfd);
            continue;
        }
        //数据库连接
        pthread_mutex_lock(&threadPool->mutex);
        MYSQL* mysql = mysql_init(NULL);
        MYSQL* ret = mysql_real_connect(mysql,
                                        "localhost",
                                        "root",
                                        "3692580147",
                                        "diskbyself",
                                        0,NULL,0);
        if(ret == NULL){
            fprintf(stderr,"%s:%s\n","mysql_real_connect",mysql_error(mysql));
        }
        LOG_ERROR_CHECK(ret,NULL,"mysql_real_connect");
        pthread_mutex_unlock(&threadPool->mutex);
        printf("数据库连接成功。\n");

        //业务
        stackDir_t* dirStack = usrname_to_dirStack(&threadPool->usrinfo,usrname);
        int tag;
        char pathname[512] = {0};
        recvTrain(netfd,&tag,pathname);
        if(tag == PUTS){
            while(1){
                int ret = getfile_c_to_s(netfd,pathname,dirStack,mysql,usrname);
                if(ret == 0 || ret == -1){
                    syslog(LOG_INFO,"%s rmdir %s.",usrname,pathname);
                    break;
                }
            }
        }else if(tag == GETS){
            putfile_s_to_c(netfd,pathname,dirStack,mysql,usrname);
            syslog(LOG_INFO,"%s rmdir %s.",usrname,pathname);
        }
        close(netfd);
    }
    return NULL;
}

int makeWorker(threadPool_t* threadPool){
    for(int i = 0; i < threadPool->tidArr.workerNum; ++i){
        pthread_create(&threadPool->tidArr.arr[i],NULL,threadFunc,threadPool);
    }
    return 0;
}
